<?php

namespace IDock\Insurance\DBIC\Response;

use IDock\Http\Response;
use IDock\Printer\EPolicyDownloadPrinter;

class EPolicyDownloadResponse extends AllDBICResponse
{

    /**
     * @var EPolicyDownloadPrinter $printer
     */
    public $printer = EPolicyDownloadPrinter::class;

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = json_decode($body, true);

        if ($this->printer) {
            $this->printer = new $this->printer;
        }

        $responseCode = $body['responseCode'] ?? '0';

        $errorMsg = $body['errorMsg'] ?? '';

        if ($responseCode != '1') {
            //保单未生效提前下载判断
            if ($errorMsg == '保单未生效不能下载电子保单！') {
                $this->printer->doing = true;
                $this->printer->finish = false;
            } else {
                $this->setError($errorMsg);
            }

            return $this;
        }
        $this->setBody($body ?? []);

        $this->result = $this->getBody()['result'] ?? [];
        $this->records = $this->result['data']['records'] ?? [];

        return $this;
    }

    public function printerInit(): Response
    {
        if ($this->printer->doing) {
            return $this;
        }
        $this->printer->doing = false;
        $this->printer->finish = true;
        $this->printer->url = $this->getRecords(0)['elecDownAddress'] ?? '';
        $this->printer->signUrl = $this->getRecords(0)['markDownAddress']??'';
        return $this;
    }
}
